// pages/cart/index.js
// 默认请求第一页
var numbers = 1;
var bool = true;
var url = getApp().globalData.ApiUrl;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    hasList: false,      //判断购物车是否有产品
    edit_name: "编辑",  
    edit: true,
    red: false,          //完成字体的颜色
    cart:[],             //购物车列表
    selectAllStatus: true,     //全选按钮的状态
    show: true,
    allimg: "https://www.zhuisushangcheng.com/data/upload/applet/gou.png",
    fanimg: "https://www.zhuisushangcheng.com/data/upload/applet/circle.png",
    totalPrice: 0,
    cart_count: '',  // 购物车商品数量
    cart_id: '', //购物车id
    allSelect: true,
    itemOne: '', //结算商品块
    goods_list: [],
    // key: wx.getStorageSync('key'),
    num: 0,
  },
  // 去逛逛
  goplay: function() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  // 编辑
  btn_edit: function(res) {
    var that = this;
    var cart = that.data.cart;
    var key = wx.getStorageSync('key');
    if (bool) {      
      for (var i in cart) {
        cart[i].selected = false;
        for (var j in cart[i].goods) {
          cart[i].goods[j].selected = false;
        }
      }
      that.setData({
        edit_name: "完成",
        edit: false,
        red: true,
        cart: cart,
        selectAllStatus: false,
        show: false,
      })
      bool = false;
    } else {
      that.setData({
        edit_name: "编辑",
        edit: true,
        red: false,
        show: true,
        selectAllStatus: true,
      })
      bool = true;
      this.onLoad();
    }
    
  },
  
  /**
   * 选择--勾选单个商品
   * @author chelfinn
   * @date 2018-09-19
   */
  selectList:function(res) {
    var idx = res.currentTarget.dataset.idx;   
		var index = res.currentTarget.dataset.index;   
		var selectAllStatus = this.data.selectAllStatus;
    var cart = this.data.cart;
		cart[index].goods[idx].selected = !cart[index].goods[idx].selected;
		if (!cart[index].goods[idx].selected){
			cart[index].selected = false;
			selectAllStatus = false;
		}else{
			for (let i in cart[index]) {
				for (let j in cart[index].goods){
					if (!cart[index].goods[j].selected){
						cart[index].selected = false;
						break;
					}else{
						cart[index].selected = true;
					}
				}
			}
			for (let i in cart){
				if (!cart[i].selected){
					selectAllStatus = false;
					break;
				}else{
					selectAllStatus = true;
				}
			}
		}
    this.setData({
      cart: cart,
			selectAllStatus : selectAllStatus
    });
    this.getTotalPrice();
  },
  /**
   * 选择--店铺所有商品
   * @author chelfinn
   * @date 2018-09-19
   */
  selectStoreGoods: function (res) {
    var index = res.currentTarget.dataset.index;
    var cart = this.data.cart;
    var selectAllStatus = this.data.selectAllStatus;
    cart[index].selected = !cart[index].selected;
		for (var i in cart[index].goods) {
			cart[index].goods[i].selected = cart[index].selected;
    }
		if (cart[index].selected){
			for (var i in cart) {
        if (!cart[i].selected) {
					selectAllStatus = false;
					break;
				}else{
					selectAllStatus = true;
				}
			}
		}else{
			selectAllStatus = false;
		}
    this.setData({
      cart: cart,
      selectAllStatus: selectAllStatus
    });
    this.getTotalPrice();
  },
  /**
   * 全选事件--选择所有
   * @author chelfinn
   * @date 2018-09-19
   */
  selectAll: function(res) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    var cart = this.data.cart;
    for (let i = 0; i < cart.length; i++) {
      cart[i].selected = selectAllStatus;
			for (let j in cart[i].goods){
				cart[i].goods[j].selected = selectAllStatus;
			}
    }
    this.setData({
      cart: cart,
      selectAllStatus: selectAllStatus
    });
    this.getTotalPrice();
  },
  /**
   * 计算价钱
   */
  getTotalPrice() {
    var cart = this.data.cart;     //获取购物车列表
		var itemOne = JSON.parse(JSON.stringify(cart)); //购物车选中类目
    let total = 0;
    var cart_id = '';
    /**
     * 获取商品价格
     */
    for (let i = 0; i < cart.length; i++) {      //循环列表中的每一项
      if (cart[i].selected) {
        for (var j in cart[i].goods) {
          total += cart[i].goods[j].goods_num * cart[i].goods[j].goods_price;
          cart_id += cart[i].goods[j].cart_id + '|' + cart[i].goods[j].goods_num+ ',';
        }                
      }else{        
        for(var j in cart[i].goods){         
          if (cart[i].goods[j].selected){            
            total += cart[i].goods[j].goods_num * cart[i].goods[j].goods_price;
            cart_id += cart[i].goods[j].cart_id + '|' + cart[i].goods[j].goods_num+ ',';
          }       
        }
      }
    }
    /**
     * 获取要结算的商品块
     */
		for (let i = itemOne.length-1; i >= 0; i--) {      //循环列表中的每一项
      if (!itemOne[i].selected) {
				for (let j = itemOne[i].goods.length-1; j>=0; j--){
					if (!itemOne[i].goods[j].selected) {
						itemOne[i].goods.splice(j, 1);
					}
				}
				// 如果店铺没有商品则删除店铺
				if (itemOne[i].goods.length == 0){
					itemOne.splice(i,1);
				}
      } 
    }
		this.setData({
			cart: cart,
      itemOne: itemOne,
			totalPrice: total.toFixed(2),
			cart_id: cart_id
		});    
  },
  
  //点击减号
  minuAcvive: function (e) {
    var that = this;
    let cart = that.data.cart;
    var idx = e.currentTarget.dataset.idx
    var index = e.currentTarget.dataset.index;
    if (cart[index].goods[idx].goods_num <= 1) {
      that.setData({
        minusStatus: true
      });
      return;
    }
    cart[index].goods[idx].goods_num--;   
    var cart_id = e.currentTarget.dataset.cart_id;
    var num = parseInt(e.currentTarget.dataset.goods_num - 1);
    var key = wx.getStorageSync("key");
    wx.showLoading({
      title: '加载中...',
    });
    wx.request({
      url: url + '/mobile/index.php?act=member_cart&op=cart_edit_quantity',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'post',
      data: {
        key: key,
        cart_id: cart_id,
        quantity: num
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.code == 400) {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        };
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    })
    
    this.getTotalPrice();
  },
  // 点击加号 
  addActive: function (e) {
    var that = this;    
    var cart = this.data.cart;
    var idx = e.currentTarget.dataset.idx
    var index = e.currentTarget.dataset.index;
    var cart_id = e.currentTarget.dataset.cart_id;
    var key = wx.getStorageSync("key");
    let quantity = parseInt(e.currentTarget.dataset.goods_num) + 1;
    if (cart[index].goods[idx].goods_num > 0) {
      that.setData({
        minusStatus: false,
      });
    }
    cart[index].goods[idx].goods_num++;    
    wx.showLoading({
      title: '加载中...',
    });
    wx.request({
      url: url + '/mobile/index.php?act=member_cart&op=cart_edit_quantity',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'post',
      data: {
        key: key,
        cart_id: cart_id,
        quantity: quantity
      },
      success: (res)=> {
        wx.hideLoading();
        if (res.data.code == 400) {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    })
    this.getTotalPrice();
  },
  // 购物车删除
  deleteList: function() {    
    var that = this;
    let cart = that.data.cart;
    var cart_id = '';
		for (let i = cart.length - 1; i >= 0; i--) {      //循环列表中的每一项
			if (!cart[i].selected) {
				for (let j = cart[i].goods.length - 1; j >= 0; j--) {
					if (cart[i].goods[j].selected) {
            cart_id += cart[i].goods[j].cart_id + ','
						cart[i].goods.splice(j, 1);
					}
				}
				// 如果店铺没有商品则删除店铺
				if (cart[i].goods.length == 0) {
					cart.splice(i, 1);
				}
			}else{
        for (let j = cart[i].goods.length - 1; j >= 0; j--) {
          if (cart[i].goods[j].selected) {
            cart_id += cart[i].goods[j].cart_id + ','
          }
        }
				cart.splice(i, 1);
			}
		}
    that.setData({
      cart: cart,
    });
    cart_id = cart_id.substr(0, cart_id.length - 1)
    this.getTotalPrice(); //计算总价
    var key = wx.getStorageSync("key");
    //请求删除接口
    wx.request({
      url: url + '/mobile/index.php?act=member_cart&op=cart_del',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'post',
      data: {
        key: key,
        cart_id: cart_id
      },
      success: (res) => {
        if(res.data.code == 200){
          wx.showToast({
            title: '删除成功',
            icon: 'none',
            duration: 2000
          });
        }else{
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  /**
   * 结算--跳转到订单也
   * @author chelfinn
   * @date 2018-09-18
   */
  buysumbit: function () {
    /**
     * log_id 参团id,自己发起的团,支付成功后返回的id，有则传，无则不传，不能穿空    pintuan_id 不为空时，为拼主的拼团号
     * pintuan    拼团的话设置为1，默认为空
     * status 1普通购买，2拼团，3秒杀
     */
    var ifcart = 1;
    var cart_id = this.data.cart_id;
    cart_id = cart_id.substr(0, cart_id.length - 1);
    var item = JSON.stringify(this.data.itemOne);
    var totalPrice = this.data.totalPrice;
    if (totalPrice == 0) {
      wx.showModal({
        title: '提示',
        content: '还未选择任何商品哦~',
      })
    } else {
      wx.navigateTo({
        url: '/pages/submit-order/index?status=1&cart_id=' + cart_id + '&ifcart=' + ifcart + '&item=' + item + '&totalPrice=' + totalPrice,
      });
    }
  },
  onLoad: function (e) {
    var that = this;
    var key = wx.getStorageSync("key");    
    if (key){
      that.carList();
    }else{
      wx.showModal({
        title: '提示',
        content: '请先登录',
        success: (res)=>{
          if (res.confirm){
            wx.navigateTo({
              url: "/pages/authorize/index" //暂时屏蔽掉，如果没有授权则跳转到授权页面
            })
          }
        }
      })
    }
   
    let list = this.data.cart;
    // 如果数据为空
    if (!list.length) {
      this.setData({
        hasList: false
      });
    }
  },
  /**
   * 获取微信购物车列表
   */
  carList: function (key) {
    var that = this;
    var key = wx.getStorageSync("key");
    wx.showLoading({
      title: '加载中,请稍后...',
    });
    wx.request({
      url: url + '/mobile/index.php?act=member_cart&op=cart_list',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'get',
      data: {
        key: key
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.hideLoading();
          var cart_id = '';
          var cart_list = res.data.datas.cart_list;
          var cart_count = res.data.datas.cart_count;
          var goods = [];
          for (var i in cart_list){
            cart_list[i].selected = true;
            goods.push(cart_list[i].goods);
          }
          for (var j in goods) {
            for (var m in goods[j]) {
              goods[j][m].selected = true;
              cart_id += goods[j][m].cart_id + '|' + goods[j][m].goods_num + ',';
            }
          }
          var sum = res.data.datas.sum;
          if (cart_list.length >0){
            that.setData({
              cart: cart_list,
              cart_id: cart_id,
              cart_count: cart_count,
              hasList: true,
              totalPrice: sum,
            });
            this.getTotalPrice();
          }   
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取购物车失败',
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  onShow: function() {
    // this.getTotalPrice();
   
  },
  // 跳转去店铺页
  toStore: function(e) {
    wx.navigateTo({
      url: '/pages/store/home/index?store_id=' + e.currentTarget.dataset.store_id,
    })
  },
  // 跳转去商品详情
  toGoodsDetails: function(e) {
    wx.navigateTo({
      url: '/pages/group-detail/index?goods_id=' + e.currentTarget.dataset.goods_id,
    })
  }
});
